import cv2
import hashlib
import time

cap = cv2.VideoCapture(0)

if not cap.isOpened():
    print("错误：无法访问摄像头")
    exit()

# 计时器初始化
last_capture = time.time()
frame_counter = 0

try:
    while True:
        ret, frame = cap.read()
        if not ret:
            print("错误：无法获取视频帧")
            break

        # 实时显示始终更新
        cv2.imshow('Camera Feed', frame)

        # 每秒处理一次
        current_time = time.time()
        if current_time - last_capture >= 5:
            # 转换为JPEG格式字节流（更接近实际存储格式）
            _, buffer = cv2.imencode('.jpg', frame)
            frame_bytes = buffer.tobytes()
            
            # 计算双哈希值
            md5_hash = hashlib.md5(frame_bytes).hexdigest()
            sha1_hash = hashlib.sha1(frame_bytes).hexdigest()
            
            # 显示帧率信息
            fps = frame_counter / (current_time - last_capture)
            print(f"[{time.strftime('%H:%M:%S')}] 帧率: {fps:.1f}fps | MD5: {md5_hash} | SHA1: {sha1_hash}")

            # 重置计时器和计数器
            last_capture = current_time
            frame_counter = 0

        frame_counter += 1

        # 退出检测（改为支持ESC键）
        if cv2.waitKey(1) in [27, ord('q')]:  # ESC或Q键退出
            break

finally:
    cap.release()
    cv2.destroyAllWindows()